import React, { PureComponent, Fragment } from 'react';
import { Form, Input, InputNumber, Checkbox, Tooltip, Icon, Select, notification } from 'antd';
import { connect } from 'dva';
import "./form.less"
class BridgeForm extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            maxPk: 999999,
            minPk: 0,
            bridgeType: 19,
            abutmentTypeList: [],
            bridgeList: [],
            bridgeTypeList: [],
            bridgeScopeList: [],
            roadlist: []
        }
        this.onConfirm = this.onConfirm.bind(this);
        this.selectBridgeType = this.selectBridgeType.bind(this)
        this.selectRoad = this.selectRoad.bind(this)
        this.validator = this.validator.bind(this)
    }


    async componentDidMount() {
        let { project, dictlist, bridgeData,loadProjectRoads,queryBridgeDetail,onLoaded,updateNewPageTitle } = this.props;
        if (onLoaded) {
            onLoaded(this);
        }
        this.setState({
            abutmentTypeList: dictlist.filter(item => item.dictType == 'abutment_type'),
            bridgeScopeList: dictlist.filter(item => item.dictType == "bridge_scope"),
            bridgeTypeList: dictlist.filter(item => item.dictType == "bridge_type"),
            loadStandard: dictlist.filter(item => item.dictType == "load_standard"),
            designReferencePeriod: dictlist.filter(item => item.dictType == "design_reference_period"),
        })
        let data = await loadProjectRoads({ projectId: project.id })
        if (data) {
            this.setState({
                roadlist: data.res
            })
        }
        if (bridgeData) {
            let res2 = await queryBridgeDetail({ id: bridgeData.bridgeId || bridgeData.id })
            if (res2) {
                if (updateNewPageTitle) {
                    updateNewPageTitle(res2.name)
                }
                this.setState({
                    bridgeData: res2
                })
            }
        }


    }
    reset() {
        let { form } = this.props;
        let values = form.getFieldsValue()
        for (const key in values) {
            if (values.hasOwnProperty(key)) {
                console.log(key)
                if (key != 'id' && key != 'projectId') {
                    values[key] = null
                }
            }
        }
        form.setFieldsValue(values)
    }
    init() {
        let { form } = this.props;
        form.resetFields()
    }
    onConfirm(params = {}) {
        let { project, mode,bridgeData,form ,addBridge,treeContext,getBridgeMainList,editBridge,getBridgeSpansById} = this.props;
        return new Promise((resolve, reject) => {
            form.validateFields((error, values) => {
                if (!error) {
                    if (values.same !== undefined && values.same !== null && values.same !== "") {
                        values.same = Number(values.same) + ''

                    }
                    if (mode == 'add') {
                       addBridge(values, async (bridge) => {
                            if (bridge != "020162") {
                                this.reset()
                            }
                            resolve(`桥梁${values.name}添加成功!`)
                            if (treeContext) {
                                let res = await getBridgeMainList({ projectId: project.id })
                                if (res && res.length) {
                                    const len=res.length
                                    for (let i = 0; i < len; i++) {
                                        let item = res[i];
                                        item.title = ' 桥梁 : ' + item.name;
                                        item.key = 'bridge' + item.id;
                                        item.eventType = 'bridge'
                                        item.eventKey = 'bridge'
                                        item.checkable = false
                                    }
                                    treeContext.updateTreeNode('bridgeData' + project.id, res)
                                }

                            }

                            if (params.onSuccess) {
                                params.onSuccess(bridge);
                            }
                        }, (error) => {
                            if (params.onError) {
                                params.onError(error);
                            }
                            reject()
                        });
                    } else {

                        editBridge(values, async (bridge) => {
                            if (treeContext) {
                                bridge.data.data.title = ' 桥梁 : ' + values.name;
                                bridge.data.data.key = 'bridge' + values.id;
                                bridge.data.data.eventType = 'bridge'
                                bridge.data.data.eventKey = 'bridge'
                                bridge.data.data.checkable = false
                                treeContext.updateTreeNodeSelf('bridge' + bridge.data.data.id, bridge.data.data)
                
                                if ( bridge.data.data.bridges &&  bridge.data.data.bridges.length) {
                                    const len2= bridge.data.data.bridges.length
                                    for (let i = 0; i < len2; i++) {
                                        let item =  bridge.data.data.bridges[i];
                                        item.title = item.name;
                                        item.key = 'bridgeChild' + item.id;
                                        item.bridgeMinId = values.id
                                        item.eventType = 'bridgeChild'
                                        item.eventKey = 'bridgeChild'
                                        item.checkable = true
                                        item.selectable = true
                                        treeContext.updateTreeNodeSelf('bridgeChild' + item.id, item)
                                    }
                                }
                                let res = getBridgeSpansById({ bridgeId: bridgeData.id })
                                if (res && res.length) {
                                    const len3=res.length
                                    for (let i = 0; i < len3; i++) {
                                        let item = res[i];
                                        item.title = item.name + ' : ' + item.code;
                                        item.key = 'botStructureDirec' + item.id;
                                        item.bridgeId = values.id
                                        item.eventType = 'botStructureDirec'
                                        item.eventKey = 'botStructureDirec'
                                        item.checkable = true
                                        item.selectable = true
                                        treeContext.updateTreeNodeSelf('botStructureDirec' + item.id, item)
                                    }
                                }

                            }

                            if (params.onSuccess) {
                                params.onSuccess(bridge.data.data);
                            }
                            resolve(`桥梁${values.name}更新成功!`)
                        }, (error) => {
                            if (params.onError) {
                                params.onError(error);
                            }
                            reject()
                        });
                    }

                } else {
                    reject()
                    if (params.onError) {
                        params.onError(error);
                    }

                }
            });
        })
    }
    selectBridgeType(e) {
        this.setState({
            bridgeType: e
        })
    }
    async selectRoad(e) {
        let res = await this.props.queryRoadLimit({ id: e })
        if (res) {
            this.setState({
                maxPk: res.maxPk,
                minPk: res.minPk
            })
        }
    }
    validator(rule, value, callback) {
        const { maxPk, minPk } = this.state;
        try {
            if (value - maxPk > 0 || value - minPk < 0) {
                callback("不在线路里程范围之内!")
            }
        } catch (err) {
            callback(err);
        }
        callback()
    }
    render() {
        const {
            form = {},
            mode,
            project,

        } = this.props;
        const { getFieldDecorator } = form;
        const { roadlist, maxPk, minPk, bridgeType, bridgeTypeList, bridgeScopeList, abutmentTypeList, bridgeData, loadStandard } = this.state;
        return (
            <Form
                style={{ marginTop: "20px" }}
                labelAlign="right"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
            >
               
                
                <Form.Item className="half" label='桥梁'>
                    {getFieldDecorator('name', {
                        rules: [
                            { required: true, message: '桥梁名称' }
                        ],
                        initialValue: mode == 'edit' && bridgeData ? bridgeData.name : null
                    })(
                        <Input placeholder="请输入桥梁名称" />
                    )}
                </Form.Item>

                {/* <Form.Item className="half" label='关联桥梁'>
                    {getFieldDecorator('refBridgeId', {
                        rules: [
                            { required: false, message: '关联桥梁' }
                        ],
                        initialValue: mode == 'edit' && bridgeData ? bridgeData.nrefBridgeIdame : undefined
                    })(
                        <Select showSearch filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        } placeholder="请选择桥梁">
                            {bridgeList && bridgeList.length > 0 ? bridgeList.map((r, i) => (
                                <Select.Option key={r.id} value={r.id}>{r.name}</Select.Option>
                            )) : ''}
                        </Select>
                    )}
                </Form.Item> */}


                <Form.Item className="half" label={<span>
                    线路&nbsp;
              <Tooltip title="请选择导入路线">
                        <Icon type="question-circle-o" />
                    </Tooltip>
                </span>}>
                    {getFieldDecorator('roadlineId', {
                        rules: [
                            { required: true, message: '线路' }
                        ],
                        initialValue: mode == 'edit' && bridgeData ? bridgeData.roadlineId : undefined
                    })(
                        <Select onSelect={this.selectRoad} disabled={mode == 'edit' ? true : false} placeholder="请选择线路">
                            {
                                roadlist.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                    )
                                })
                            }

                        </Select>
                    )}
                </Form.Item>
                <Form.Item className="half" label='桥台位置'>
                    {getFieldDecorator('abutmentType', {
                        rules: [
                            { required: true, message: '桥台位置' }
                        ],
                        initialValue: mode == "edit" && bridgeData ? bridgeData.abutmentType : undefined
                    })(
                        <Select placeholder="请选择桥台位置">
                            {
                                abutmentTypeList && abutmentTypeList.length ? abutmentTypeList.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                    )
                                }) : undefined
                            }

                        </Select>
                    )}
                </Form.Item>
                <Form.Item className={`half ${mode == 'edit' ? '' : 'none'}`} label='起始桩号(m)'>
                    {getFieldDecorator('startStation', {
                        rules: [
                            { required: false, message: '起始桩号' }
                        ],
                        initialValue: mode == 'edit' && bridgeData ? bridgeData.startStation : undefined
                    })(
                        <InputNumber type="number" disabled={mode == 'edit' ? true : false} min={minPk} max={maxPk} placeholder="请输入起始桩号" />
                    )}
                </Form.Item>

                <Form.Item className={`half ${mode == 'edit' ? '' : 'none'}`} label='结束桩号(m)'>
                    {getFieldDecorator('endStation', {
                        rules: [
                            { required: false, message: '结束桩号' }
                        ],
                        initialValue: mode == 'edit' && bridgeData ? bridgeData.endStation : undefined
                    })(
                        <InputNumber type="number" disabled={mode == 'edit' ? true : false} min={minPk} max={maxPk} placeholder="请输入结束桩号" />
                    )}
                </Form.Item>

                <Form.Item className="half" label='中心桩号(m)'>
                    {getFieldDecorator('midStation', {
                        rules: [
                            { required: true, message: '中心桩号' },
                            {
                                validator: this.validator
                            }
                        ],
                        initialValue: mode == 'edit' && bridgeData ? bridgeData.midStation : undefined
                    })(
                        <InputNumber disabled={mode == 'edit' ? true : false} placeholder="请输入中心桩号" />
                    )}
                </Form.Item>

                <Form.Item className="half" label='桥梁类型'>
                    {getFieldDecorator('bridgeType', {
                        rules: [
                            { required: true, message: '桥梁类型' }
                        ],
                        initialValue: mode == 'edit' && bridgeData ? bridgeData.bridgeType : undefined
                    })(
                        <Select placeholder="请选择桥梁类型" showSearch filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        } disabled={mode == 'edit' ? true : false}>
                            {
                                bridgeTypeList.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                    )
                                })
                            }

                        </Select>
                    )}
                </Form.Item>
                <Form.Item className="half" label='设计载荷'>
                    {getFieldDecorator('loadStandard', {
                        rules: [
                            { required: true, message: '设计载荷' }
                        ],
                        initialValue: mode == 'edit' && bridgeData ? bridgeData.loadStandard : undefined
                    })(
                        <Select placeholder="请选择设计载荷">
                            {
                                loadStandard && loadStandard.length ? loadStandard.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                    )
                                }) : undefined
                            }

                        </Select>
                    )}
                </Form.Item>
                <Form.Item className="half" label='设计基准期(年)'>
                    {getFieldDecorator('designReferencePeriod', {
                        rules: [
                            { required: true, message: '设计基准期' }
                        ],
                        initialValue: mode == 'edit' && bridgeData ? bridgeData.designReferencePeriod : 100
                    })(

                        <InputNumber type="number" type="number" min={0} placeholder="请输入设计基准期" />

                    )}
                </Form.Item>
                <Form.Item className="half" label='桥幅类型'>
                    {getFieldDecorator('bridgeScope', {
                        rules: [
                            { required: true, message: '必填' }
                        ],
                        initialValue: mode == 'edit' && bridgeData ? bridgeData.bridgeScope : undefined
                    })(
                        <Select disabled={mode == 'edit' ? true : false} showSearch placeholder="请选择桥幅类型" filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        } onChange={this.selectBridgeType}>
                            {
                                bridgeScopeList.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                    )
                                })
                            }

                        </Select>
                    )}
                </Form.Item>
                {
                    bridgeType && bridgeType == 19 ? <Fragment> <Form.Item className="half" label='桥宽(m)'>
                        {getFieldDecorator('width', {
                            rules: [
                                { required: true, message: '桥宽' }
                            ],
                            initialValue: mode == 'edit' && bridgeData ? bridgeData.width : null
                        })(
                            <InputNumber type="number" placeholder="请输入桥宽" />
                        )}
                    </Form.Item><div className="half"></div></Fragment> : <Fragment>
                            <Form.Item className="half" label='左幅桥宽(m)'>
                                {getFieldDecorator('leftWidth', {
                                    rules: [
                                        { required: true, message: '左幅桥宽' }
                                    ],
                                    initialValue: mode == 'edit' && bridgeData ? bridgeData.width : null
                                })(
                                    <InputNumber type="number" placeholder="请输入左幅桥宽" />
                                )}
                            </Form.Item>
                            <Form.Item className="half" label='右幅桥宽(m)'>
                                {getFieldDecorator('rightWidth', {
                                    rules: [
                                        { required: true, message: '右幅桥宽' }
                                    ],
                                    initialValue: mode == 'edit' && bridgeData ? bridgeData.width : null
                                })(
                                    <InputNumber type="number" placeholder="请输入右幅桥宽" />
                                )}
                            </Form.Item>
                            <Form.Item style={{ width: "100%", float: "left" }} labelCol={{ span:6}}
                                wrapperCol={{ span:18}} label='左右桥幅保持一致'>
                                {getFieldDecorator('same', {
                                    valuePropName: 'checked',
                                    initialValue: mode == 'edit' ? new Boolean(bridgeData.same) : true
                                })(
                                    <Checkbox
                                    >
                                    </Checkbox>
                                )}
                            </Form.Item>
                        </Fragment>
                }
 {
                    mode!='add'?<Form.Item
                    className="half"
                    label='ID'
                    style={{ display: 'none' }}>
                    {getFieldDecorator('id', {
                        rules: [
                            { required: mode == 'edit' ? true : false, message: '必填' }
                        ],
                        initialValue: mode == 'edit' && bridgeData ? bridgeData.id : null

                    })(
                        <Input />
                    )}
                </Form.Item>:undefined
                }


                
                    <Form.Item
                    className="half hide"
                    label='ID'>
                    {getFieldDecorator('projectId', {
                        rules: [
                            { required: true, message: '必填' }
                        ],
                        initialValue: project.id
                    })(
                        <Input />
                    )}
                </Form.Item>
            </Form>
        );
    }
}

export default connect(
    ({

    }) => {
        return {}
    },
    dispatch => ({
        addBridge: (values, onSuccess, onError) => dispatch({
            type: 'bridge/addBridgeMain',
            payload: {
                values, onSuccess, onError
            }
        }),
        getBridgeSpansById: (values) => dispatch({
            type: 'refSpans/getBridgeSpansById',
            payload: values
        }),
        editBridge: (values, onSuccess, onError) => dispatch({
            type: 'bridge/edit',
            payload: {
                values, onSuccess, onError
            }
        }),
        queryBridgeDetail: (values) => dispatch({
            type: 'bridge/queryBridgeDetail',
            payload: values
        }),
        queryRoadLimit: (values) => dispatch({
            type: 'bridge/queryRoadLimit',
            payload: values
        }),
        getBridgeMainList: (values) => dispatch({
            type: 'bridge/getBridgeMainList',
            payload: values
        }),
        loadProjectRoads: (values) => dispatch({
            type: 'refRoads/loadProjectRoads',
            payload: values
        }),
    })
)(Form.create('bridge', {

})(BridgeForm));